import {
    createSlice
} from "@reduxjs/toolkit";

import { useSelector } from "react-redux";

export type TPanes = {
    title: string,
    key: string,
    closable: boolean
}

export type TPage = {
    current: number,
    pageSize: number,
    total: number,
}

type TCommonState = {
    panes: TPanes[],
    pageInfo: TPage,
    loading: boolean
}

const initialState: TCommonState = {
    panes: [
        {
            title: "主页",
            key: "/",
            closable: false
        }
    ],
    pageInfo: {
        current: 1,
        pageSize: 1,
        total: 1
    },
    loading: false
}

const commonSlice = createSlice({
    name: "common",
    initialState,
    reducers: {
        changeTitleByKey(state, { payload }) {
            const info: TPanes = state.panes.find(v => v.key === payload.key) as TPanes;
            info.title = payload.title;
        },
        changeLoading(state, { payload }) {
            // console.log(1111111, payload);
            state.loading = payload;
        },
        // 添加panes
        addPanes(state, { payload }) {
            const info: TPanes = state.panes.find((v: TPanes) => v.key === payload.key) as TPanes;
            if (!info) {
                state.panes.push(payload);
            }
        },
        // 删除：根据下标删除
        delPandes(state, { payload }) {
            state.panes.splice(payload, 1);
        },
        delPanesByKey(state, { payload }){
            const index = state.panes.findIndex(v=>v.key === payload);
            state.panes.splice(index,1);
        },
        changePageInfo(state, { payload }) {
            state.pageInfo = payload;
        }
    }
})


export const { delPanesByKey,changeTitleByKey,addPanes,delPandes,changeLoading,changePageInfo} = commonSlice.actions;
export const useSelectorCommon = () => useSelector((state: any) => state.common);
export default commonSlice.reducer;
